package com.example.xunua_zhinengjiaotong.utils;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil extends OkHttpClient{

    public JSONObject connectServer(String requestJson, MyApp myApp, String action) throws IOException, JSONException {

        //1、获取okhttpClient
        OkHttpClient client=new OkHttpClient();

        //2、创建requestbody对象         arg1:请求的数据格式   arg2:具体的请求数据==》{"SenseName":"co2"}
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestJson);

        //3、创建request对象
        Request request=new Request.Builder().url("http://"+myApp.getIp()+":8890/type/jason/action/"+action).post(requestBody).build();

        //4、通过请求连接服务器，获取服务器返回的响应
        Call call = client.newCall(request);

        //5、执行call（链接）请求，获取相应
        Response response = call.execute();

        //6、获取响应对象中的数据
        String data = response.body().string();
//        Log.e("HttpUtil", "connectServer: "+data );
        JSONObject jsonObject=new JSONObject(data);
        return jsonObject;
    }

    /**
     * 返回的是JsonArray
     * @param requestJson
     * @param myApp
     * @param action
     * @return
     * @throws IOException
     * @throws JSONException
     */
    public JSONArray connectServer_JsonArray(String requestJson, MyApp myApp, String action) throws IOException, JSONException {

        //1、获取okhttpClient
        OkHttpClient client=new OkHttpClient();

        //2、创建requestbody对象         arg1:请求的数据格式   arg2:具体的请求数据==》{"SenseName":"co2"}
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestJson);

        //3、创建request对象
        Request request=new Request.Builder().url("http://"+myApp.getIp()+":8890/type/jason/action/"+action).post(requestBody).build();

        //4、通过请求连接服务器，获取服务器返回的响应
        Call call = client.newCall(request);

        //5、执行call（链接）请求，获取相应
        Response response = call.execute();

        //6、获取响应对象中的数据
        String data = response.body().string();
//        Log.e("HttpUtil", "connectServer: "+data );
//        JSONObject jsonObject=new JSONObject(data);
        JSONArray jsonArray=new JSONArray(data);
        return jsonArray;
    }
}
